package com.luych.toolbox.docker.service.service;

import com.luych.toolbox.common.enums.DockerRegistryStatus;
import com.luych.toolbox.common.feign.intf.base.service.UserFeign;
import com.luych.toolbox.common.feign.param.docker.service.DockerRegistryParam;
import com.luych.toolbox.common.feign.view.base.service.UserView;
import com.luych.toolbox.common.feign.view.docker.service.DockerRegistryView;
import com.luych.toolbox.common.page.PageParam;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseConvert;
import com.luych.toolbox.common.service.base.BaseService;
import com.luych.toolbox.common.service.exception.HttpException;
import com.luych.toolbox.common.service.page.SpringPageParamAdapter;
import com.luych.toolbox.common.service.page.SpringPageResultAdapter;
import com.luych.toolbox.docker.service.constant.Constant;
import com.luych.toolbox.docker.service.dao.DockerRegistryDao;
import com.luych.toolbox.docker.service.entity.DockerRegistry;
import com.luych.toolbox.docker.service.job.DockerRegistryHealthCheckJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class DockerRegistryService extends BaseService<DockerRegistryView, DockerRegistryParam, DockerRegistry>
        implements ApplicationListener<ApplicationReadyEvent> {

    private static final BaseConvert<DockerRegistryParam, DockerRegistry> dockerRegistryParamToEntity = DockerRegistry::new;
    private static final BaseConvert<DockerRegistry, DockerRegistryView> dockerRegistryEntityToView = DockerRegistryView::new;

    private final Boolean rescheduleWhenStart;
    private final Scheduler scheduler;
    private final DockerRegistryDao dockerRegistryDao;
    private final UserFeign userFeign;

    @Autowired
    public DockerRegistryService(@Value("${spring.quartz.rescheduleWhenStart:false}") Boolean rescheduleWhenStart,
                                 Scheduler scheduler,
                                 DockerRegistryDao dockerRegistryDao,
                                 UserFeign userFeign) {
        super(dockerRegistryDao, dockerRegistryParamToEntity, dockerRegistryEntityToView);
        this.rescheduleWhenStart = rescheduleWhenStart;
        this.scheduler = scheduler;
        this.dockerRegistryDao = dockerRegistryDao;
        this.userFeign = userFeign;
    }

    @Override
    protected DockerRegistryView fill(DockerRegistryView view) {
        dockerRegistryDao.findById(view.getId()).map(DockerRegistry::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return view;
    }

    @Override
    public DockerRegistryView save(DockerRegistryParam param) {
        // check owner
        UserView owner = userFeign.get(param.getOwnerId());
        if (owner == null) {
            throw new HttpException(HttpStatus.BAD_REQUEST, Constant.DOCKER_REGISTRY_SAVE_OWNER_ERROR);
        }
        // save docker registry
        DockerRegistry dockerRegistryParam = dockerRegistryParamToEntity.apply(param);
        dockerRegistryParam.setStatus(DockerRegistryStatus.WAITING);
        DockerRegistry dockerRegistryResult = dockerRegistryDao.save(dockerRegistryParam);
        return this.fill(dockerRegistryEntityToView.apply(dockerRegistryResult));
    }

    private JobKey getJobKey(String id) {
        return new JobKey(id, DockerRegistryHealthCheckJob.class.getName());
    }

    private JobDetail getJobDetail(String id) {
        Map<String, Object> jobParam = new HashMap<String, Object>() {{
            this.put("id", id);
        }};
        return JobBuilder.newJob(DockerRegistryHealthCheckJob.class)
                .withIdentity(this.getJobKey(id))
                .usingJobData(new JobDataMap(jobParam))
                .build();
    }

    private Trigger getJobTrigger(String id) {
        return TriggerBuilder.newTrigger()
                .withIdentity(id, DockerRegistryHealthCheckJob.class.getName())
                .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(10))
                .build();
    }

    @Override
    public DockerRegistryView create(DockerRegistryParam param) {
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getUrl(), "Param url can't be empty");
        Assert.notNull(param.getUser(), "Param user can't be empty");
        Assert.notNull(param.getPass(), "Param pass can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check name exists
        if (dockerRegistryDao.findByName(param.getName()).isPresent()) {
            throw new HttpException(HttpStatus.CONFLICT, Constant.DOCKER_REGISTRY_SAVE_NAME_USED);
        }

        // save
        DockerRegistryView view = this.save(param);

        // schedule
        try {
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // return
        return view;
    }

    @Override
    public DockerRegistryView modify(DockerRegistryParam param) {
        Assert.notNull(param.getId(), "Param id can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getUrl(), "Param url can't be empty");
        Assert.notNull(param.getUser(), "Param user can't be empty");
        Assert.notNull(param.getPass(), "Param pass can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check name exists
        Optional<DockerRegistry> dataAgentOptOfName = dockerRegistryDao.findByName(param.getName());
        if (dataAgentOptOfName.isPresent() && !dataAgentOptOfName.get().getId().equals(param.getId())) {
            throw new HttpException(HttpStatus.CONFLICT, Constant.DOCKER_REGISTRY_SAVE_NAME_USED);
        }

        // save
        DockerRegistryView view = this.save(param);

        // schedule
        try {
            scheduler.deleteJob(this.getJobKey(view.getId()));
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // return
        return view;
    }

    @Override
    public void remove(String id) {
        // TODO: 2023/6/29
        
        // schedule
        try {
            scheduler.deleteJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // delete
        dockerRegistryDao.deleteById(id);
    }

    public PageResult<DockerRegistryView> pageByKeyword(PageParam pageParam, String keyword) {
        Page<DockerRegistry> page;
        if (StringUtils.isEmpty(keyword)) {
            page = dockerRegistryDao.findAll(new SpringPageParamAdapter(pageParam));
        } else {
            page = dockerRegistryDao.findByNameLikeOrUrlLike('%' + keyword + '%', '%' + keyword + '%', new SpringPageParamAdapter(pageParam));
        }
        PageResult<DockerRegistry> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(dockerRegistryEntityToView).convert(this::fill);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (Boolean.TRUE.equals(rescheduleWhenStart)) {
            List<DockerRegistry> dockerRegistrys = dockerRegistryDao.findAll();
            for (DockerRegistry dockerRegistry : dockerRegistrys) {
                try {
                    scheduler.deleteJob(this.getJobKey(dockerRegistry.getId()));
                    scheduler.scheduleJob(this.getJobDetail(dockerRegistry.getId()), this.getJobTrigger(dockerRegistry.getId()));
                } catch (SchedulerException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
